package com.xci.platform.upload;

import cn.hutool.core.io.FileUtil;
import com.xci.platform.core.BoolMessage;
import com.xci.platform.helper.StringHelper;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class WebUploadFile implements IUploadFile {
    /**
     * 上传文件
     *
     * @param files   上传文件对象集合
     * @param options 上传选项
     * @return 返回上传文件信息
     */
    @Override
    public List<BoolMessage<UploadFileInfo>> upload(List<MultipartFile> files, UploadFileOptions options) {
        List<BoolMessage<UploadFileInfo>> result = new ArrayList<>();
        if (files == null || files.size() <= 0) return result;
        for (MultipartFile file : files) {
            BoolMessage<UploadFileInfo> r = upload(file, options);
            result.add(r);
        }
        return result;
    }

    /**
     * 上传文件
     *
     * @param file    上传文件对象
     * @param options 上传选项
     * @return 返回上传文件信息
     */
    @Override
    public BoolMessage<UploadFileInfo> upload(MultipartFile file, UploadFileOptions options) {
        if (file == null || file.getSize() == 0) {
            return new BoolMessage<>(false, "请指定要上传的文件");
        }
        if (StringHelper.isBlank(options.getUploadPath())) {
            return new BoolMessage<>(false, "请指定文件上传的目录");
        }
        if (options.getAllowMaxSize() <= 0) {
            return new BoolMessage<>(false, "请指定允许文件上传的最大文件大小");
        }
        if (options.getAllowExtension() == null || options.getAllowExtension().length == 0) {
            return new BoolMessage<>(false, "请指定允许文件上传的扩展名");
        }

        String originalFilename = file.getOriginalFilename();
        if (StringHelper.isNotBlank(originalFilename)) {
            originalFilename = originalFilename.replace("&", "").replace("?", "");
        }

        String fileName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        if (StringHelper.isBlank(fileName)) {
            return new BoolMessage<>(false, "请指定上传文件的文件名");
        }
        if (StringHelper.isBlank(extName)) {
            return new BoolMessage<>(false, "请指定上传文件的扩展名");
        }

        extName = extName.toLowerCase();
        long allowFileMaxSize = options.getAllowMaxSize() * 1024;
        if (file.getSize() > allowFileMaxSize) {
            String msg = StringHelper.format("上传文件大小超过限制,系统限制最大为{}", FileUtil.readableFileSize(allowFileMaxSize));
            return new BoolMessage<>(false, msg);
        }
        String finalExtName = extName;
        if (Arrays.stream(options.getAllowExtension()).noneMatch(p -> p.toLowerCase().equals(finalExtName))) {
            String msg = StringHelper.format("上传文件扩展名禁止。只允许{}格式", String.join(",", options.getAllowExtension()));
            return new BoolMessage<>(false, msg);
        }

        String virtualFolder = options.getUploadPath();
        if (!virtualFolder.substring(virtualFolder.length() - 1).equals("/")) {
            virtualFolder = virtualFolder + "/";
        }
        String virtualFileName = StringHelper.format("{}.{}", StringHelper.guid(), extName);
        String virtualFilePath = (virtualFolder + virtualFileName);

        File saveFileObject = new File(new File("").getAbsolutePath() + virtualFilePath);
        try {
            FileUtil.mkParentDirs(saveFileObject);
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFileObject));
        } catch (IOException e) {
            return new BoolMessage<>(false, e.getMessage());
        }

        UploadFileInfo info = new UploadFileInfo();
        info.setName(originalFilename);
        info.setContentType(file.getContentType());
        info.setVirtualUrl(virtualFilePath);
        info.setSize(file.getSize());
        return new BoolMessage<>(info);
    }
}
